package com.start.core.log;

import com.alibaba.fastjson2.JSONObject;
import com.start.common.tools.IPTools;
import com.start.common.tools.SpringContextTools;
import com.start.core.annotations.StartLog;
import com.start.core.entity.StartLogEntity;
import com.start.core.service.StartLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import jakarta.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
public class StartLogAspect {

    @Autowired
    private StartLogService startLogService;

    @Pointcut("@annotation(com.start.core.annotations.StartLog)")
    public void sysLogPointcut() {
    }

    @Around("sysLogPointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        HttpServletRequest request = SpringContextTools.getHttpServletRequest();
        if (request.getMethod().equalsIgnoreCase("option")) {
            return point.proceed();
        }
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        StartLog startLog = method.getAnnotation(StartLog.class);
        if (startLog == null || !startLog.save()) return point.proceed();
        Object[] args = point.getArgs();
        String className = point.getTarget().getClass().getName();
        String methodName = signature.getName();
        String sourceMethod = className + "." + methodName + "()";
        String argsStr = null;
        StartLogEntity startLogEntity = new StartLogEntity();
        if (startLog.saveMethodArgs()) {
            try {
                argsStr = JSONObject.toJSONString(args);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        String requestURI = request.getRequestURI();
        startLogEntity.setTitle(startLog.value());
        startLogEntity.setAction(startLog.action());
        startLogEntity.setLogType(startLog.logType());
        startLogEntity.setRequestIp(IPTools.getIpAddr(request));
        startLogEntity.setRequestParameter(argsStr);
        startLogEntity.setSourceMethod(sourceMethod);
        startLogEntity.setPath(requestURI);
        startLogEntity.setRequestMethod(request.getMethod().toLowerCase());
        StartLogStore.getStore().save(startLogEntity);
        return point.proceed();
    }
}
